<?php
declare(strict_types=1);

namespace app\model;

use think\Model;
use think\facade\Cache;

class ExpressServiceProvider extends Model
{
    protected $name = 'express_service_provider';
    
    protected $autoWriteTimestamp = true;
    
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    // 状态
    const STATUS_ENABLED = 1;
    const STATUS_DISABLED = 2;

    /**
     * 获取利润配置
     */
    public function getProfitConfig(): array
    {
        // 尝试从缓存获取
        $cacheKey = "express_profit:{$this->id}";
        $config = Cache::get($cacheKey);

        if (!$config) {
            // 从数据库获取
            $config = [
                'merchant_profit_rate' => $this->merchant_profit_rate ?? 0,
                'platform_profit_rate' => $this->platform_profit_rate ?? 0
            ];

            // 缓存配置
            Cache::set($cacheKey, $config, 3600);
        }

        return $config;
    }

    /**
     * 更新利润配置
     */
    public function updateProfitConfig(float $merchantProfitRate, float $platformProfitRate): bool
    {
        // 验证利润率
        if ($merchantProfitRate < 0 || $merchantProfitRate > 100) {
            throw new \Exception('商家利润率必须在0-100之间');
        }
        if ($platformProfitRate < 0 || $platformProfitRate > 100) {
            throw new \Exception('平台利润率必须在0-100之间');
        }
        if ($merchantProfitRate + $platformProfitRate > 100) {
            throw new \Exception('商家利润率与平台利润率之和不能超过100');
        }

        // 更新数据
        $result = $this->save([
            'merchant_profit_rate' => $merchantProfitRate,
            'platform_profit_rate' => $platformProfitRate
        ]);

        if ($result) {
            // 清除缓存
            Cache::delete("express_profit:{$this->id}");
        }

        return $result;
    }

    /**
     * 获取可用的快递服务商列表
     */
    public static function getEnabledList(): array
    {
        // 尝试从缓存获取
        $cacheKey = 'express_providers:enabled';
        $list = Cache::get($cacheKey);

        if (!$list) {
            // 从数据库获取
            $list = self::where('status', self::STATUS_ENABLED)
                ->field('id,service_code,company_name,company_code,service_type,channel,description,weight_index,is_insured,insure_fee')
                ->order('id', 'asc')
                ->select()
                ->toArray();

            // 缓存列表
            Cache::set($cacheKey, $list, 3600);
        }

        return $list;
    }

    /**
     * 启用快递服务商
     */
    public function enable(): bool
    {
        if ($this->status == self::STATUS_ENABLED) {
            return true;
        }

        $result = $this->save(['status' => self::STATUS_ENABLED]);

        if ($result) {
            // 清除缓存
            Cache::delete('express_providers:enabled');
        }

        return $result;
    }

    /**
     * 禁用快递服务商
     */
    public function disable(): bool
    {
        if ($this->status == self::STATUS_DISABLED) {
            return true;
        }

        $result = $this->save(['status' => self::STATUS_DISABLED]);

        if ($result) {
            // 清除缓存
            Cache::delete('express_providers:enabled');
        }

        return $result;
    }

    /**
     * 关联价格缓存
     */
    public function priceCaches()
    {
        return $this->hasMany(ExpressPriceCache::class, 'express_service_provider_id');
    }
} 